@file:Suppress("UNCHECKED_CAST", "unused")

package com.virtualightning.mvvm.impl.adapter

import com.virtualightning.core.processor.adapter.anno.ViewHolderEventBinder
import com.virtualightning.mvvm.utils.AppUtils

/**
 *  Anchor : Create by CimZzz
 *  Time : 2021/11/22 17:34
 *  万能 Adapter 反射注入工具
 */
object UniverseInject {
	/**
	 * 指令处理桥
	 */
	private val commandBridge: HashMap<String, ViewHolderEventBinder<*, AdapterCommand>> = HashMap()

	/**
	 * 处理 Adapter 命令
	 *
	 * @param instance Any 处理对象
	 * @param command AdapterCommand Adapter 命令
	 *
	 * @note 需要注意的是，此方法需要搭配 core.anno 和 core.process 一同使用，生成中间文件，才可以借助反射
	 * 执行对应方法
	 */
	fun handleCommand(instance: Any, command: AdapterCommand) {
		AppUtils.strictMainThread()
		val instanceName = instance::class.java.canonicalName ?: return
		val bridge = commandBridge[instanceName] ?: run {
			val foundBridge = kotlin.runCatching {
				val foundClass = Class.forName("${instanceName}___AdapterEventBinder")
				foundClass.newInstance()
			}.getOrNull() ?: EmptyBinder
			val typedBridge = foundBridge as ViewHolderEventBinder<*, AdapterCommand>
			commandBridge[instanceName] = typedBridge
			typedBridge
		}
		bridge.handleCommand(instance, command)
	}


	/**
	 * 空 Binder，为优化效率而生
	 */
	private object EmptyBinder : ViewHolderEventBinder<Unit, AdapterCommand>() {
		/**
		 * 触发事件回调接口
		 * @param instance T 所依附的实例
		 * @param command E Adapter 命令
		 */
		override fun handleAdapterCommand(instance: Unit, command: AdapterCommand) {
		}
	}
}